## ----setup, include=FALSE----------------------------------------------------------
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, results = "hide", fig.width= 9, fig.height=7) 



## ----------------------------------------------------------------------------------
#install.packages("cregg")
#cregg used to evaluate conjoint data
library(cregg)
library(knitr)


## ----------------------------------------------------------------------------------
library(readr)
library(tidyverse)
library(dplyr)


#Load in the original conjoint data
conjoint_data <- read_csv("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Original Data/Chile_Conjoint_June.csv")


#Select those who have passed attention check
conjoint_data <- conjoint_data%>% filter(IMC == "Otra")



## ----------------------------------------------------------------------------------

Chile_conjoint <- conjoint_data%>%
  dplyr::select(caseID = caseID,
                contest_no,
                Profile,
                Female, 
                Age, 
                Income,  
                Education,    
                Chosen_country, 
                "¿Quién puede votar?", 
                "Creación de leyes",
                "Matrimonio igualitario",
                "Presidencia",
                "Reglas para votar",
                "Sistema de partidos",
                "Sistema electoral")%>%
  
  mutate(Sex = 
           case_when(Female == 'Femenino' ~ "Female",
                     Female == 'Masculino' ~ "Male"),
         
         
         Education_eng = 
           case_when(Education == 'Primario incompleto' ~ "Some primary",
                     Education == 'Primario completo' ~ "Primary",
                     Education == 'Secundario incompleto' ~ "Some secondary",
                     Education == 'Secundario completo' ~ "Secondary",
                     Education == 'Terciario incompleto' ~ "Some post-secondary",
                     Education == 'Terciario completo' ~ "Post-secondary",
                     Education == 'Universitario incompleto' ~ "Some university",
                     Education == 'Universitario completo' ~ "University",
                     Education == 'Posgrado completo o incompleto' ~ "Post-graduate"
                    # Education == 'Prefiero no decirlo' ~ "Prefer not to say",

                     
                     
                     ),
         
            Education_cut = 
           case_when(Education == 'Primario incompleto' ~ "Primary",
                     Education == 'Primario completo' ~ "Primary",
                     Education == 'Secundario incompleto' ~ "Secondary",
                     Education == 'Secundario completo' ~ "Secondary",
                     Education == 'Terciario incompleto' ~ "Post-secondary",
                     Education == 'Terciario completo' ~ "Post-secondary",
                     Education == 'Universitario incompleto' ~ "University",
                     Education == 'Universitario completo' ~ "University",
                     Education == 'Posgrado completo o incompleto' ~ "Post-graduate"
                    # Education == 'Prefiero no decirlo' ~ "Prefer not to say",

                     
                     
                     ),
         
             Education_census = 
           case_when(Education == 'Primario incompleto' ~ "Primary",
                     Education == 'Primario completo' ~ "Primary",
                     Education == 'Secundario incompleto' ~ "Secondary",
                     Education == 'Secundario completo' ~ "Secondary",
                     Education == 'Terciario incompleto' ~ "Post-secondary or more",
                     Education == 'Terciario completo' ~ "Post-secondary or more",
                     Education == 'Universitario incompleto' ~ "Post-secondary or more",
                     Education == 'Universitario completo' ~ "Post-secondary or more",
                     Education == 'Posgrado completo o incompleto' ~ "Post-secondary or more"
                    # Education == 'Prefiero no decirlo' ~ "Prefer not to say",

                     
                     
                     ),
         
         
                  
            
         Income_eng = 
           case_when(Income == 'Ningún ingreso' ~ "No income",
                     
                    Income == 'Menos de 125,000 pesos' ~ "Less than 125,000 pesos",
                    
                     Income == 'Entre 125,000 y 190,000 pesos' ~ "Between 125,000 and 190,000 pesos",
                     Income == 'Entre 190,001 y 225,000 pesos' ~ "Between 190,001 and 225,000 pesos",
                     Income == 'Entre 225,001 y 255,000 pesos' ~ "Between 225,001 and 255,000 pesos",
                     Income == 'Entre 255,001 y 300,000 pesos' ~ "Between 255,001 and 300,000 pesos",
                     Income == 'Entre 300,001 y 335,000 pesos' ~ "Between 300,001 and 335,000 pesos",
                     Income == 'Entre 335,001 y 375,000 pesos' ~ "Between 335,001 and 375,000 pesos",
                     Income == 'Entre 375,001 y 420,000 pesos' ~ "Between 375,001 and 420,000 pesos",
                     Income == 'Entre 420,001 y 470,000 pesos' ~ "Between 420,001 and 470,000 pesos",
                    
                     Income == 'Entre 470,001 y 525,000 pesos' ~ "Between 470,001 and 525,000 pesos",

                     Income == 'Entre 525,001 y 600,000 pesos' ~ "Between 525,001 and 600,000 pesos",
                     
                      Income == 'Entre 600,001 y 690,000 pesos' ~ "Between 600,001 y 690,000 pesos pesos",
                     
                      Income == 'Entre 690,001 y 830,000 pesos' ~ "Between 690,001 y 830,000 pesos",
                     
                     Income == 'Entre 830,001 y 1.000,000 pesos"' ~ "Between 830,001 and 1.000,000 pesos",
                     
                     Income == 'Entre 1.000,001 y 1,500,000 pesos' ~ "Between 1.000,001 and 1,500,000 pesos",
                     
                      Income == 'Más de 1,500,000 pesos' ~ "More than 1,500,000 pesos"
                     ),
         
         
           Netquest_ses = 
           case_when(Income == 'Ningún ingreso' ~ "E",
                     
                    Income == 'Menos de 125,000 pesos' ~ "E",
                    
                     Income == 'Entre 125,000 y 190,000 pesos' ~ "E",
                     Income == 'Entre 190,001 y 225,000 pesos' ~ "E",
                     Income == 'Entre 225,001 y 255,000 pesos' ~ "E",
                     Income == 'Entre 255,001 y 300,000 pesos' ~ "E",
                     Income == 'Entre 300,001 y 335,000 pesos' ~ "E",
                     Income == 'Entre 335,001 y 375,000 pesos' ~ "E",
                     Income == 'Entre 375,001 y 420,000 pesos' ~ "E",
                     Income == 'Entre 420,001 y 470,000 pesos' ~ "D",
                    
                     Income == 'Entre 470,001 y 525,000 pesos' ~ "D",

                     Income == 'Entre 525,001 y 600,000 pesos' ~ "D",
                     
                      Income == 'Entre 600,001 y 690,000 pesos' ~ "D",
                     
                      Income == 'Entre 690,001 y 830,000 pesos' ~ "C3",
                     
                     Income == 'Entre 830,001 y 1.000,000 pesos"' ~ "C3",
                     
                     Income == 'Entre 1.000,001 y 1,500,000 pesos' ~ "C2",
                     
                      Income == 'Más de 1,500,000 pesos' ~ "C1b to A"
                     ),
    
           Income_level = 
           case_when(Income == 'Ningún ingreso' ~ "255,000 or less",
                     
                    Income == 'Menos de 125,000 pesos' ~ "255,000 or less",
                    
                     Income == 'Entre 125,000 y 190,000 pesos' ~ "255,000 or less",
                     Income == 'Entre 190,001 y 225,000 pesos' ~ "255,000 or less",
                     Income == 'Entre 225,001 y 255,000 pesos' ~ "255,000 or less",
                     Income == 'Entre 255,001 y 300,000 pesos' ~ "Between 255,001 and 375,000",
                     Income == 'Entre 300,001 y 335,000 pesos' ~ "Between 255,001 and 375,000",
                     Income == 'Entre 335,001 y 375,000 pesos' ~ "Between 255,001 and 375,000",
                     Income == 'Entre 375,001 y 420,000 pesos' ~ "Between 375,001 and 525,000",
                     Income == 'Entre 420,001 y 470,000 pesos' ~ "Between 375,001 and 525,000",
                    
                     Income == 'Entre 470,001 y 525,000 pesos' ~ "Between 375,001 and 525,000",

                     Income == 'Entre 525,001 y 600,000 pesos' ~ "Between 525,001 and 830,000",
                     
                      Income == 'Entre 600,001 y 690,000 pesos' ~ "Between 525,001 and 830,000",
                     
                      Income == 'Entre 690,001 y 830,000 pesos' ~ "Between 525,001 and 830,000",
                     
                     Income == 'Entre 830,001 y 1.000,000 pesos"' ~ "830,001 or more",
                     
                     Income == 'Entre 1.000,001 y 1,500,000 pesos' ~ "830,001 or more",
                     
                      Income == 'Más de 1,500,000 pesos' ~ "830,001 or more"
                     ),
         
         
          Age_cut = cut(Age, breaks = c(-Inf, 36, 56, Inf), labels = c("36 years or less", "37 to 56 years", "Over 56 years")), # By 10
    
           Age_netquest_cut = cut(Age, breaks = c(-Inf, 24, 34, 44, 54, 64, 74, Inf), labels = c("24 years or less", "25 to 34 years", "35 to 44 years","45 to 54 years","55 to 64 years","65 to 74 years","Over 75 years")), # By 10
    
         

    

    
    'Voting Rule' = 
            
            case_when(`Reglas para votar` == 'Votar es un acto voluntario' ~ 'Voluntary voting',
                             
                    `Reglas para votar` == "El voto es obligatorio por ley, pero quienes no votan no reciben ninguna" ~ 'Compulsory voting with no punishment',
                    
                    `Reglas para votar` == 'El voto es obligatorio por ley, y quienes no voten deben pagar una multa de 3 UTM' ~ 'Compulsory voting with a 3 UTM fine'),
          
          'Electoral System' =         
            case_when(`Sistema electoral` == 'A los partidos se les asigna escaños en el Congreso en proporción a la cantidad de votos que obtienen' ~ 'Seats assigned in proportion to votes obtained',
                             
                    `Sistema electoral` == "El partido que obtiene la mayor parte de los votos suele ganar la mayoría de los escaños en el Congreso, incluso si obtiene menos de la mitad de los votos" ~ 'Party with most votes gets majority of seats, even without majority of votes'),
          
          'Party System' =         
            case_when(`Sistema de partidos` == 'Varios partidos compiten en las elecciones y obtienen escaños en el Congreso' ~ 'Multiple parties compete in elections and get seats',
                             
                    `Sistema de partidos` == "En las elecciones, compiten dos partidos principales y obtienen escaños en el Congreso" ~ 'Two parties compete in elections and get seats'),
           'Same-sex Marriage' =         
            case_when(`Matrimonio igualitario` == 'El matrimonio entre personas del mismo sexo es ilegal' ~ 'Same-sex marriage is illegal',
                             
                    `Matrimonio igualitario` == "Los matrimonios de personas del mismo sexo están protegidos por la ley" ~ 'Same-sex marriage is legally protected'),
          
               'Presidency' =         
            case_when(`Presidencia` == 'El presidente tiene el poder de establecer leyes y políticas' ~ 'President has the power to shape laws and policies',
                             
                    `Presidencia` == "El presidente solo tiene un poder simbólico" ~ 'President only has symbolic power'),
          
          
                'Law Creation' =         
            case_when(`Creación de leyes` == 'El presidente puede crear nuevas leyes por decreto, sin votos del Congreso' ~ 'President creates new laws by decree, without congressional approval',
                             
                    `Creación de leyes` == "Las nuevas leyes propuestas deben obtener el apoyo de la mayoría en el Congreso" ~ 'New laws need support of a congressional majority'),
          
          
                  'Who Can Vote' =         
      
            case_when(`¿Quién puede votar?` == 'Todos los adultos tienen el derecho de votar' ~ 'All adults have the right to vote',
                             
                    `¿Quién puede votar?` == "Las personas que continuamente dicen cosas malas sobre Chile no tienen derecho al voto" ~ 'People that say bad things about Chile cannot vote', 
                    
                    
                     `¿Quién puede votar?` == "Las personas que no están informadas sobre política y actualidad no tienen derecho al voto" ~ 'People not informed about politics and current events cannot vote')
                  
          
          
          )
  


## ----------------------------------------------------------------------------------


# Sex
Chile_conjoint$Sex <- as.factor(Chile_conjoint$Sex)


# Education

Chile_conjoint$Education_eng <- factor(Chile_conjoint$Education_eng, levels = c("Some primary","Primary",  "Some secondary", "Secondary","Some post-secondary","Post-secondary", "Some university","University", "Post-graduate"))


Chile_conjoint$Education_cut <- factor(Chile_conjoint$Education_cut, levels = c("Primary", "Secondary", "Post-secondary", "University", "Post-graduate"))



# Age


Chile_conjoint$Age_cut <- factor(Chile_conjoint$Age_cut, levels = c("36 years or less", "37 to 56 years", "Over 56 years"))

# Income
Chile_conjoint$Income_level <- factor(Chile_conjoint$Income_level, levels = c("255,000 or less", "Between 255,001 and 375,000", "Between 375,001 and 525,000", "Between 525,001 and 830,000", "830,001 or more"))




## ----------------------------------------------------------------------------------

Chile_conjoint$`Voting Rule` <- factor(Chile_conjoint$`Voting Rule`,
                levels = c("Voluntary voting", "Compulsory voting with no punishment", "Compulsory voting with a 3 UTM fine"))



Chile_conjoint$`Electoral System` <- factor(Chile_conjoint$`Electoral System`,
                levels = c("Party with most votes gets majority of seats, even without majority of votes", "Seats assigned in proportion to votes obtained"))


Chile_conjoint$`Party System` <- factor(Chile_conjoint$`Party System`,
                levels = c("Two parties compete in elections and get seats", "Multiple parties compete in elections and get seats"))



Chile_conjoint$`Same-sex Marriage` <- factor(Chile_conjoint$`Same-sex Marriage`,
                levels = c("Same-sex marriage is illegal", "Same-sex marriage is legally protected"))



Chile_conjoint$`Presidency` <- factor(Chile_conjoint$`Presidency`,
                levels = c("President has the power to shape laws and policies", "President only has symbolic power"))



Chile_conjoint$`Law Creation` <- factor(Chile_conjoint$`Law Creation`,
                levels = c("President creates new laws by decree, without congressional approval", "New laws need support of a congressional majority"))



Chile_conjoint$`Who Can Vote` <- factor(Chile_conjoint$`Who Can Vote`,
                levels = c("All adults have the right to vote", "People that say bad things about Chile cannot vote", "People not informed about politics and current events cannot vote"))



## ----------------------------------------------------------------------------------
Sex_table <-  as.data.frame(prop.table(table(Chile_conjoint$Sex)))

Sex_table <- Sex_table%>% 
  rename(Gender = Var1)%>%
  rename(Sample = Freq)%>%
  mutate(Nat_rep = c(.511, .489))


## ----------------------------------------------------------------------------------
Age_table <-  as.data.frame(prop.table(table(Chile_conjoint$Age_netquest_cut)))

Age_table <- Age_table%>% 
  rename(Age = Var1)%>%
  rename(Sample = Freq)%>%
  mutate(Nat_rep = c(.1465/.8,
                     .1610/.8, 
                     .1371/.8 , 
                     .1358/.8, 
                     .110/.8, 
                     .0663/.8, 
                     .042/.8))



## ----------------------------------------------------------------------------------

library(gridExtra)
Sex_grob <- tableGrob(Sex_table)
Age_grob <- tableGrob(Age_table)



pdf("Demos_Chile_Netquest.pdf")
grid.arrange(Sex_grob, Age_grob, ncol = 1, nrow = 2)
dev.off()


## ----------------------------------------------------------------------------------

Chile_conjoint$Education_census <- factor(Chile_conjoint$Education_census,
                levels = c("Primary", "Secondary", "Post-secondary or more"))



Education_table <-  as.data.frame(prop.table(table(Chile_conjoint$Education_census)))




Education_table <- Education_table%>% 
  rename(Education = Var1)%>%
  rename(Sample = Freq)%>%
  
  mutate(Nat_rep = c(.256,
                     .446,
                     .298))




## ----------------------------------------------------------------------------------
library(survey)


## ----------------------------------------------------------------------------------
Chile_conjoint_omit <- Chile_conjoint%>%
    mutate(Sex_num = 
           case_when(Sex == 'Female' ~ 1,
                     Sex == 'Male' ~ 0),
           Sex_num = as.numeric(Sex_num),
           
           Education_num = 
           case_when(Education_census == 'Primary' ~ 1,
                     Education_census == 'Secondary' ~ 2,
                     Education_census == 'Post-secondary or more' ~ 3),
           
          Education_num = as.numeric(Education_num), 
          
          Age_num =  
            case_when(Age_netquest_cut == '24 years or less' ~ 1,
                      Age_netquest_cut == '25 to 34 years' ~ 2,
                      Age_netquest_cut == '35 to 44 years' ~ 3,
                      Age_netquest_cut == '45 to 54 years' ~ 4,
                      Age_netquest_cut == '55 to 64 years' ~ 5,
                      Age_netquest_cut == '65 to 74 years' ~ 6,
                      Age_netquest_cut == 'Over 75 years' ~ 7,


            ),
          
          Age_num = as.numeric(Age_num))%>%
  drop_na(Sex_num, Education_num, Age_num)
  
  
  



## ----------------------------------------------------------------------------------
set.seed(123)
dummy_survey_unweighted <- svydesign(ids = ~caseID, 
                                     data = Chile_conjoint_omit, 
                                     weights = NULL)


Sex_dist <- tibble(Sex_num = c(0, 1), Freq = nrow(Chile_conjoint_omit)*c(0.489, 0.511))

Age_dist <- tibble(Age_num = seq(1, 7, 1), Freq = nrow(Chile_conjoint_omit)*c(0.183125, 0.201250, 0.171375, 0.169750, 0.137500, 0.082875, 0.052500))


Education_dist <- tibble(Education_num = seq(1, 3, 1), Freq = nrow(Chile_conjoint_omit)*c(0.256, 0.446, 0.298))

survey_rake <- rake(design = dummy_survey_unweighted,
                          sample.margins = list(~Sex_num, ~Age_num, ~Education_num),
                          population.margins = list( Sex_dist, Age_dist, Education_dist))






## ----------------------------------------------------------------------------------

#rename so the demos are the same
Sex_table <- rename(Sex_table, Subgroup = Gender)

Age_table <- rename(Age_table, Subgroup = Age)

Education_table <- rename(Education_table, Subgroup = Education)

demo_tables <- rbind(Sex_table,
                     Age_table,
                     Education_table)
demo_tables <- tibble(demo_tables)



## ----------------------------------------------------------------------------------
library(xtable)
xtable(demo_tables)


## ----------------------------------------------------------------------------------
svymean(Chile_conjoint_omit[, c("Sex_num","Age_num", "Education_num")],
        design = dummy_survey_unweighted,
        na.rm = TRUE)



## ----------------------------------------------------------------------------------
svymean(Chile_conjoint_omit[, c("Sex_num","Age_num", "Education_num")],
        design = survey_rake,
        na.rm = TRUE)



## ----------------------------------------------------------------------------------
Chile_conjoint_omit$Weight <- 1/survey_rake[["prob"]]

Chile_conjoint_omit <- Chile_conjoint_omit%>%
  dplyr::select(caseID,
                Weight,
                contest_no,
                Profile,
                Chosen_country,
                Sex,
                Education_cut,
                Age_cut,
                Income_level,
                `Voting Rule`,
                `Electoral System`,
                `Party System`,
                `Same-sex Marriage`,
                `Presidency`,
                `Law Creation`,
                `Who Can Vote`)


saveRDS(Chile_conjoint_omit, "~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Analysis Data/Chile_conjoint_June.rds")


## ----------------------------------------------------------------------------------
#Clear and read in analysis data
rm(list=ls())
library(cregg)
library(ggplot2)

set.seed(1234)
#For mac
Chile_conjoint <- readRDS("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Analysis Data/Chile_conjoint_June.rds")



## ----------------------------------------------------------------------------------
mm_main <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID, 
weights = ~Weight, estimate = "mm")


## ---- eval = TRUE,echo=FALSE, results = "asis"-------------------------------------
knitr::kable(mm_main)


## ----------------------------------------------------------------------------------
library(cregg)
set.seed(1234)
amce_main <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID, weights = ~Weight, estimate = "amce")




## ---- eval = TRUE,echo=FALSE, results = "asis"-------------------------------------
knitr::kable(amce_main)


## ----------------------------------------------------------------------------------



p1 <- plot(
  cregg::cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID,weights = ~Weight, estimate = "mm"), vline = 0.5
) + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
  #ylab(NULL) +
  theme(axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "none", 
           legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank()) + 
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )+  
  ggplot2::geom_text(
    aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
    colour = "black", 
    size = 4,
    position = position_nudge(y = .5)
  ) 



p2 <- plot(
  cj(Chile_conjoint,
     Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID,weights = ~Weight, estimate = "amce"), vline = 0
) + 
#geom_point(size = 0.1, stroke = 0, shape = 16) +
  ggplot2::scale_x_continuous(
    limits = c(-0.3, 0.3), 
    breaks = c(-0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3)
  )+  
  ggplot2::geom_text(
    aes(label = ifelse(is.na(std.error), "", sprintf("%0.3f (%0.3f)", estimate, std.error))),
    colour = "black", 
    size = 4,
    position = position_nudge(y = .5)
 ) + 
   geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
  
  ylab(NULL) +
  theme(axis.text.y = element_blank(), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "none", 
           legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank()) 
  





## ----------------------------------------------------------------------------------

p.main <- gridExtra::grid.arrange(p1, p2, ncol = 2, nrow=1, widths = c(2.8, 1))


ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/MM_ACME_plot_June.pdf", width = 11, height = 7, units = "in", p.main)


## ----------------------------------------------------------------------------------

mm_gender <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
alpha = .16, 
id= ~caseID, estimate = "mm", weights = ~ Weight, by = ~Sex)





## ---- eval = FALSE,echo=FALSE, results = "asis"------------------------------------
## kable(mm_gender)


## ----------------------------------------------------------------------------------

mm_gender <- na.omit(mm_gender)


plot.gender <- plot(mm_gender, group = "Sex", vline = .5, legend_title = "Sex") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
  
      geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = .3, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) + 

   
#  ggplot2::geom_text(
#    aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
#    colour = "black", 
  #  size = 3,
#    position = position_nudge(y = .5)
 # )+

  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )

plot.gender


## ---- eval = FALSE, include=FALSE--------------------------------------------------
## 
## 
## #ggsave("C:/Users/neils/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/gender_suplot.pdf", width = 8.5, height = 6, units = "in", plot.gender)


## ---- messages = FALSE, results = "asis"-------------------------------------------


Chile_conjoint_omit <- na.omit(Chile_conjoint)

cj_anova(Chile_conjoint_omit, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Sex)




## ----------------------------------------------------------------------------------
mm_education <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, weights = ~ Weight, estimate = "mm",
alpha = .16, 
by = ~ Education_cut)


## ---- eval = FALSE,echo=FALSE, results = "asis"------------------------------------
## #kable(mm_education)


## ----------------------------------------------------------------------------------

mm_education$BY <- factor(mm_education$BY, levels = c("Primary", "Secondary", "Post-secondary", "University", "Post-graduate"))


plot.education <- plot(mm_education, group = "Education_cut", vline = .5, legend_title = "Education") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
      geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
       #    legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 10)) +  
   
  # ggplot2::geom_text(
  #   aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
  #   colour = "black", 
  #   size = 3,
  #   position = position_nudge(y = .5)
  # ) +
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )
# +
#   facet_wrap(. ~ BY, drop=TRUE)



plot.education


## ---- eval = FALSE, include=FALSE--------------------------------------------------
## 
## 
## #ggsave("C:/Users/neils/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_education.pdf", width = 10, height = 12, units = "in", plot.education)


## ---- messages = FALSE, results = "asis"-------------------------------------------

cj_anova(Chile_conjoint_omit, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Education_cut)




## ----------------------------------------------------------------------------------

mm_age <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
id= ~caseID, estimate = "mm", 
alpha = .16, weights = ~ Weight,
by = ~Age_cut)



## ----------------------------------------------------------------------------------
plot.age <- plot(mm_age, group = "Age_cut", vline = .5, legend_title = "Age") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
      geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 10)) +
  
  
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )
     
#  ggplot2::geom_text(
  #  aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
 #   colour = "black", 
 #   size = 3,
 #   position = position_nudge(y = .5)
  #) +
 # facet_wrap(. ~ BY, drop=TRUE)


plot.age


## ---- eval = FALSE, include=FALSE--------------------------------------------------
## 
## #ggsave("C:/Users/neils/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_age.pdf", width = 10, height = 6, units = "in", plot.age)


## ---- messages = FALSE, results = "asis"-------------------------------------------

cj_anova(Chile_conjoint_omit, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Age_cut)




## ---- message=FALSE----------------------------------------------------------------

mm_income <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, estimate = "mm", 
alpha = .16, weights = ~ Weight,
by = ~ Income_level)



## ---- eval = FALSE,echo=FALSE, results = "asis"------------------------------------
## #kable(mm_income)


## ---- message = FALSE--------------------------------------------------------------

mm_income$BY <- factor(mm_income$BY, levels = c("255,000 or less", "Between 255,001 and 375,000", "Between 375,001 and 525,000", "Between 525,001 and 830,000", "830,001 or more"))


plot.income <- plot(mm_income, group = "Income_level", vline = .5, legend_title = "Income") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
  
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
       strip.text.x = element_text(size = 6)) + 
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )
# +  
#   ggplot2::geom_text(
#     aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
#     colour = "black", 
#     size = 3,
#     position = position_nudge(y = .5)
#   ) + 
#   facet_wrap(. ~ BY, drop=TRUE)

plot.income


## ---- eval = FALSE, include=FALSE--------------------------------------------------
## 
## 
## #ggsave("C:/Users/neils/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_income.pdf", width = 10, height = 12, units = "in", plot.income)


## ---- messages = FALSE, results = "asis"-------------------------------------------

cj_anova(Chile_conjoint_omit, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Income_level)




## ---- eval = TRUE------------------------------------------------------------------

library(gtable)    
library(grid)
library(gridExtra) 
# Get the widths
g.gender <- ggplotGrob(plot.gender)
g.education <- ggplotGrob(plot.education)
g.age <- ggplotGrob(plot.age)
g.income <- ggplotGrob(plot.income)


# The parts that differs in width
leg.gender <- convertX(sum(with(g.gender$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.education <- convertX(sum(with(g.education$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.age <- convertX(sum(with(g.age$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.income <- convertX(sum(with(g.income$grobs[[15]], grobs[[1]]$widths)), "mm")


g.gender$widths <- g.income$widths
g.education$widths <- g.income$widths
g.age$widths <- g.income$widths


# Add an empty column of "abs(diff(widths)) mm" width on the right of 
# legend box for gA (the smaller legend box)
g.gender$grobs[[15]] <- gtable_add_cols(g.gender$grobs[[15]], unit(abs(diff(c(leg.gender, leg.income))), "mm"))


g.education$grobs[[15]] <- gtable_add_cols(g.education$grobs[[15]], unit(abs(diff(c(leg.education, leg.income))), "mm"))

g.age$grobs[[15]] <- gtable_add_cols(g.age$grobs[[15]], unit(abs(diff(c(leg.age, leg.income))), "mm"))







## ---- eval = TRUE------------------------------------------------------------------
grid.newpage()
plot.gender.arrange <- grid.arrange(g.gender, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/gender_subplot_June.pdf", width = 11, height = 8, units = "in", plot.gender.arrange)


## ---- eval = TRUE------------------------------------------------------------------
grid.newpage()
plot.education.arrange <- grid.arrange(g.education, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/education_subplot_June.pdf", width = 11, height = 8, units = "in", plot.education.arrange)


## ---- eval = TRUE------------------------------------------------------------------
grid.newpage()
plot.age.arrange <- grid.arrange(g.age, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/age_subplot_June.pdf", width = 11, height = 8, units = "in", plot.age.arrange)


## ---- eval = TRUE------------------------------------------------------------------
grid.newpage()
plot.income.arrange <- grid.arrange(g.income, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/income_subplot_June.pdf", width = 11, height = 8, units = "in", plot.income.arrange)


## ----------------------------------------------------------------------------------


p.mm.unweight <- plot(
  cregg::cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID, estimate = "mm"), vline = 0.5
) + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
  #ylab(NULL) +
  theme(axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "none", 
           legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank()) + 
  ggplot2::scale_x_continuous(
    limits = c(0.1, 0.85), 
    breaks = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  ) + 
  ggplot2::geom_text(
    aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
    colour = "black", 
    size = 4,
    position = position_nudge(y = .5)
  ) 



p.amce.unweight <- plot(
  cj(Chile_conjoint,
     Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, id= ~caseID, estimate = "amce"), vline = 0
) + 
#geom_point(size = 0.1, stroke = 0, shape = 16) +
  ggplot2::scale_x_continuous(
    limits = c(-0.3, 0.3), 
    breaks = c(-0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3)
  ) + 
  ggplot2::geom_text(
    aes(label = ifelse(is.na(std.error), "", sprintf("%0.3f (%0.3f)", estimate, std.error))),
    colour = "black", 
    size = 4,
    position = position_nudge(y = .5)
 ) + 
   geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
  
  ylab(NULL) +
  theme(axis.text.y = element_blank(), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "none", 
           legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank()) 
  






## ----------------------------------------------------------------------------------

p.main.unweighted <- gridExtra::grid.arrange(p.mm.unweight, p.amce.unweight, ncol = 2, nrow=1, widths = c(2.8, 1))


ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/MM_ACME_unweighted_June.pdf", width = 11, height = 7, units = "in", p.main.unweighted)


## ----------------------------------------------------------------------------------

mm_gender_unweighted <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
alpha = .16, 
id= ~caseID, estimate = "mm", by = ~Sex)





## ----------------------------------------------------------------------------------
plot.gender.unweighted <- plot(mm_gender_unweighted, group = "Sex", vline = .5, legend_title = "Sex") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
    
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = .3, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) + 

   
  # ggplot2::geom_text(
  #   aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
  #   colour = "black", 
  #   size = 3,
  #   position = position_nudge(y = .5)
  # ) +

  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)) 
  
 
  #  +  
  # facet_wrap(. ~ BY, drop=TRUE)



## ----------------------------------------------------------------------------------
mm_education_unweighted <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, estimate = "mm",
alpha = .16, 
by = ~ Education_cut)


## ----------------------------------------------------------------------------------
mm_education_unweighted$BY <- factor(mm_education_unweighted$BY, levels = c("Primary", "Secondary", "Post-secondary", "University", "Post-graduate"))


plot.education.unweighted <- plot(mm_education_unweighted, group = "Education_cut", vline = .5, legend_title = "Education") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
    
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
       #    legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) +  
   
  #  ggplot2::geom_text(
  #   aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
  #   colour = "black",
  #   size = 2,
  #   position = position_nudge(y = .5)
  # ) +
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8))
  # # +
  # facet_wrap(. ~ BY, drop=TRUE)


## ----------------------------------------------------------------------------------

mm_age_unweighted <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
id= ~caseID, estimate = "mm", alpha = .16, by = ~Age_cut)



## ----------------------------------------------------------------------------------
plot.age.unweighted <- plot(mm_age_unweighted, group = "Age_cut", vline = .5, legend_title = "Age") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
    
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) +
  
  
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )
# +  
#      
#   ggplot2::geom_text(
#     aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
#     colour = "black", 
#     size = 2,
#     position = position_nudge(y = .5)
#   )
#     +
#   facet_wrap(. ~ BY, drop=TRUE)




## ---- message=FALSE----------------------------------------------------------------

mm_income_unweighted <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, estimate = "mm", 
alpha = .16, by = ~ Income_level)



## ---- message = FALSE--------------------------------------------------------------

mm_income_unweighted$BY <- factor(mm_income_unweighted$BY, levels = c("255,000 or less", "Between 255,001 and 375,000", "Between 375,001 and 525,000", "Between 525,001 and 830,000", "830,001 or more"))


plot.income.unweighted <- plot(mm_income_unweighted, group = "Income_level", vline = .5, legend_title = "Income") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
    
    geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
  
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
          # legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
       strip.text.x = element_text(size = 6)) + 
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  ) 
# +
#   ggplot2::geom_text(
#     aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
#     colour = "black", 
#     size = 2,
#     position = position_nudge(y = .5)
#   )
# + 
#   facet_wrap(. ~ BY, drop=TRUE)



## ---- eval = TRUE------------------------------------------------------------------

library(gtable)    
library(grid)
library(gridExtra) 
# Get the widths
g.gender.unweighted <- ggplotGrob(plot.gender.unweighted)
g.education.unweighted <- ggplotGrob(plot.education.unweighted)
g.age.unweighted <- ggplotGrob(plot.age.unweighted)
g.income.unweighted <- ggplotGrob(plot.income.unweighted)


# The parts that differs in width
leg.gender.unweighted <- convertX(sum(with(g.gender.unweighted$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.education.unweighted <- convertX(sum(with(g.education.unweighted$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.age.unweighted <- convertX(sum(with(g.age.unweighted$grobs[[15]], grobs[[1]]$widths)), "mm")
leg.income.unweighted <- convertX(sum(with(g.income.unweighted$grobs[[15]], grobs[[1]]$widths)), "mm")


g.gender.unweighted$widths <- g.income.unweighted$widths
g.education.unweighted$widths <- g.income.unweighted$widths
g.age.unweighted$widths <- g.income.unweighted$widths


# Add an empty column of "abs(diff(widths)) mm" width on the right of 
# legend box for gA (the smaller legend box)
g.gender.unweighted$grobs[[15]] <- gtable_add_cols(g.gender.unweighted$grobs[[15]], unit(abs(diff(c(leg.gender.unweighted, leg.income.unweighted))), "mm"))


g.education.unweighted$grobs[[15]] <- gtable_add_cols(g.education.unweighted$grobs[[15]], unit(abs(diff(c(leg.education.unweighted, leg.income.unweighted))), "mm"))

g.age.unweighted$grobs[[15]] <- gtable_add_cols(g.age.unweighted$grobs[[15]], unit(abs(diff(c(leg.age.unweighted, leg.income.unweighted))), "mm"))







## ---- eval = TRUE------------------------------------------------------------------
grid.newpage()
plot.gender.unweighted.arrange <- grid.arrange(g.gender.unweighted, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_gender_unweighted_June.pdf", width = 11, height = 8, units = "in", plot.gender.unweighted.arrange)


## ---- eval = TRUE------------------------------------------------------------------
grid.newpage()
plot.education.unweighted.arrange <- grid.arrange(g.education.unweighted, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_education_unweighted_June.pdf", width = 11, height = 8, units = "in", plot.education.unweighted.arrange)


## ---- eval = TRUE------------------------------------------------------------------
grid.newpage()
plot.age.unweighted.arrange <- grid.arrange(g.age.unweighted, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_age_unweighted_June.pdf", width = 11, height = 8, units = "in", plot.age.unweighted.arrange)


## ---- eval = TRUE------------------------------------------------------------------
grid.newpage()
plot.income.unweighted.arrange <- grid.arrange(g.income.unweighted, nrow = 1)



ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/subplot_income_unweighted_June.pdf", width = 11, height = 8, units = "in", plot.income.unweighted.arrange)


## ---- messages = FALSE, warning = FALSE--------------------------------------------

Chile_conjoint$contest_no <- as.factor(Chile_conjoint$contest_no)
mm_contest <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, 
id= ~caseID, estimate = "mm",weights = ~ Weight,
alpha = .16,
by = ~contest_no)



## ---- eval = FALSE,echo=FALSE, results = "asis"------------------------------------
## #kable(mm_contest)


## ----------------------------------------------------------------------------------
plot.contest <- plot(mm_contest, group = "contest_no", vline = .5, legend_title = "Task") + 
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
        geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
       #    legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) +  
   
 # ggplot2::geom_text(
  #  aes(label = sprintf("%0.3f (%0.3f)", estimate, std.error)),
 #   colour = "black", 
 #   size = 2,
   # position = position_nudge(y = .5)
  #) +
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  )

plot.contest


## ----------------------------------------------------------------------------------

ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/carryover_suplot_June.pdf", width = 11, height = 8, units = "in", plot.contest)


## ---- messages = FALSE, results = "asis"-------------------------------------------
cj_anova(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~contest_no)




## ----------------------------------------------------------------------------------

Chile_conjoint$Profile <- as.factor(Chile_conjoint$Profile)
mm_profile <- cj(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`,
id= ~caseID, estimate = "mm",weights = ~ Weight,
alpha = .16,
by = ~Profile)



## ---- eval = FALSE,echo=FALSE, results = "asis"------------------------------------
## #kable(mm_profile)


## ----------------------------------------------------------------------------------

plot.profile <- 

  plot(mm_profile, group  ="Profile", vline = .5) + 

  
  guides(fill = guide_legend(reverse = TRUE)) +

  
     geom_hline(yintercept=c( 4.5, 7.5, 10.5, 13.5, 16.5, 19.5), 
                color = "grey50", size=.2) + 
        geom_hline(yintercept=c(1.5, 2.5, 5.5, 8.5, 11.5, 14.5, 17.5, 20.5, 21.5), 
                color = "grey60", size=.2, linetype = "dashed") + 
#geom_point(size = 0.1, stroke = 0, shape = 16) + 
 # ylab(NULL) +
  theme(#axis.text.y = element_blank(), 
    axis.text.y = element_text(size = 10, vjust = 0.5,face="bold"), 
        axis.text.x = element_text(size = 6, hjust = 0.5, vjust = 1), 
          axis.ticks = element_line(colour = "grey50"), 
          plot.title = element_text(face = "bold"), 
          legend.position = "right", 
       #    legend.title = element_blank(),
          panel.grid.major.x = element_blank(), 
         panel.grid.minor.x = element_blank(), 
            panel.grid.major.y = element_blank(),
       # panel.grid.minor.y =element_blank(),
        panel.background = element_blank(),
          strip.text.x = element_text(size = 8)) +
      scale_fill_discrete(breaks = c("1","2")) +
  ggplot2::scale_x_continuous(
    limits = c(0.2, 0.85), 
    breaks = c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
  ) 

plot.profile


## ----------------------------------------------------------------------------------

ggsave("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Figures/profile_suplot_June.pdf", width = 11, height = 8, units = "in", plot.profile)


## ---- messages = FALSE, results = "asis"-------------------------------------------
cj_anova(Chile_conjoint, Chosen_country ~ `Voting Rule` + `Electoral System` + `Party System` +
`Same-sex Marriage` + `Presidency` + `Law Creation` + `Who Can Vote`, by = ~Profile)




## ---- eval = FALSE-----------------------------------------------------------------
## ## ---- echo=FALSE-----------------------------------------------------
## #library(knitr)
## 
## purl("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Command Files/Chileans_Want_Supplementary.Rmd")
## 
## 
## 


## ---- eval = FALSE, echo = FALSE---------------------------------------------------
## sink("Chileans_Want_Supplementary_June.txt")
## 
## source(("~/Dropbox/Chile New Constitution/R&P Submission/Data Analysis/Command Files/Chileans_Want_Supplementary.R"),echo=T, max.deparse.length=1e3, encoding = "UTF-8")
## sink()
## 

